<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目标题" prop="tcname">
        <el-input
          v-model="queryParams.tcname"
          placeholder="请输入项目标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学校ID" prop="tcxxid">
<!--        <el-input
          v-model="queryParams.tcxxid"
          placeholder="请输入学校ID"
          clearable
          @keyup.enter="handleQuery"
        /> -->
		<el-select v-model="queryParams.tcxxid" placeholder="请选择学校">
		  <el-option
		    v-for="d in dept_self"
		    :key="d.value"
		    :label="d.label"
		    :value="d.value"
		  />
		</el-select>
      </el-form-item>
      <el-form-item label="评分标准" prop="typeid">
<!--        <el-input
          v-model="queryParams.typeid"
          placeholder="请输入评分标准ID"
          clearable
          @keyup.enter="handleQuery"
        /> -->
		
		<el-select filterable v-model="queryParams.typeid" placeholder="体测评分标准">
			<el-option
			  v-for="d in tctypeList"
			  :key="d.id"
			  :label="d.xmflTitle"
			  :value="d.id"
			/>
		</el-select>
      </el-form-item>
	  
<!-- 	  
	  <el-form-item label="创建者" prop="createby">
	    <el-input
	      v-model="queryParams.createby"
	      placeholder="请输入创建者"
	      clearable
	      @keyup.enter="handleQuery"
	    />
	  </el-form-item>
	  <el-form-item label="开始时间" prop="sd">
	    <el-date-picker clearable
	      v-model="queryParams.sd"
	      type="date"
	      value-format="YYYY-MM-DD"
	      placeholder="请选择开始时间">
	    </el-date-picker>
	  </el-form-item>
	  <el-form-item label="结束时间" prop="ed">
	    <el-date-picker clearable
	      v-model="queryParams.ed"
	      type="date"
	      value-format="YYYY-MM-DD"
	      placeholder="请选择结束时间">
	    </el-date-picker>
	  </el-form-item>
	  -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['tcname:tcname:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['tcname:tcname:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['tcname:tcname:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['tcname:tcname:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tcnameList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="名称分类id" align="center" prop="id" />
      <el-table-column label="项目标题" align="center" prop="tcname" />
      <el-table-column label="学校ID" align="center" prop="tcxxid" >
        <template #default="scope">
          <span v-for="d in dept_self">
			  {{scope.row.tcxxid==d.value?d.label:'' }}
		  </span>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createby" />
      <el-table-column label="开始时间" align="center" prop="sd" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.sd, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="ed" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.ed, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="评分标准ID" align="center" prop="typeid" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['tcname:tcname:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['tcname:tcname:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改体测名称分类 用于区分哪次体测  本次体测的项目对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body  :disabled="auform">
      <el-form ref="tcnameRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目标题" prop="tcname">
          <el-input v-model="form.tcname" placeholder="请输入项目标题" />
        </el-form-item>
        <el-form-item label="学校ID" prop="tcxxid">
          <!-- <el-input v-model="form.tcxxid" placeholder="请输入学校ID" /> -->
		  <el-select v-model="form.tcxxid" placeholder="请选择学校">
		    <el-option
		      v-for="d in dept_self"
		      :key="d.value"
		      :label="d.label"
		      :value="d.value"
		    />
		  </el-select>
        </el-form-item>
        <el-form-item label="评分标准" prop="typeid">
          <!-- <el-input v-model="form.typeid" placeholder="请输入评分标准ID" /> -->
		  <el-select filterable v-model="form.typeid" placeholder="体测评分标准" :disabled="auform">
		  	<el-option
		  	  v-for="d in tctypeList"
		  	  :key="d.id"
		  	  :label="d.xmflTitle"
		  	  :value="d.id"
		  	/>
		  </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="sd">
          <el-date-picker clearable
            v-model="form.sd"
            type="date"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="ed">
          <el-date-picker clearable
            v-model="form.ed"
            type="date"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择结束时间">
          </el-date-picker>
        </el-form-item>
		<el-divider content-position="center">体测名称分类 - 项目</el-divider>
				
		  <el-table :data="tcProjectList" @selection-change="handleTcProjectTpSelectionChange" ref="tcProjectTpRef" max-height="400">
		    <el-table-column type="selection" width="50" align="center" prop="id" />
					<el-table-column type="index" label="序号" width="55" />
		    <el-table-column label="名称" align="center" prop="xmMc"/>
		  </el-table>
		</el-form>
		<template #footer  v-if="auform == false">
		  <div class="dialog-footer">
		    <el-button type="primary" @click="submitForm">确 定</el-button>
		    <el-button @click="cancel">取 消</el-button>
		  </div>
		</template>
<!-- 		
        <el-divider content-position="center">体测名称分类  体测项目关联信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddTcTcnameTp">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteTcTcnameTp">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="tcTcnameTpList" :row-class-name="rowTcTcnameTpIndex" @selection-change="handleTcTcnameTpSelectionChange" ref="tcTcnameTp">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
	  -->
	  
    </el-dialog>
  </div>
</template>

<script setup name="Tcname">
import { listTcname, getTcname, delTcname, addTcname, updateTcname } from "@/api/tc/tcname";
import { listProject} from "@/api/tc/project";
import { listTctype,getTctype} from "@/api/tc/tctype";
import { checkPermi, checkRole } from "@/utils/permission"; // 1. 导入权限判断函数
import { listDept } from "@/api/system/dept";
import useUserStore from "@/store/modules/user";

const { proxy } = getCurrentInstance();

const tcnameList = ref([]);
// const tcTcnameTpList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedTcTcnameTp = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const tcProjectList = ref([]);
const tcProjectTpRef =  ref(null);
const checkedTcProjectTp = ref([]);
const auform = ref(true);
const tctypeList = ref([]);
const tmpProPar={pageNum: 1,pageSize: 999,xmStatus:'1'};
const tmpGetPar=ref({"pageNum": 1,"pageSize": 500});
const dept_self = ref([]);
const userStore = useUserStore();

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    tcname: null,
    tcxxid: -1,
    createby: null,
    sd: null,
    ed: null,
    typeid: null
  },
  rules: {
    tcname: [
      { required: true, message: "项目标题不能为空", trigger: "blur" }
    ],
	tcxxid: [
	  { required: true, message: "学校不能为空", trigger: "blur" }
	],
	sd: [
	  { required: true, message: "开始时间不能为空", trigger: "blur" }
	],
	ed: [
	  { required: true, message: "结束时间不能为空", trigger: "blur" }
	],
	typeid: [
	  { required: true, message: "评分标准不能为空", trigger: "blur" }
	],
  }
});

const { queryParams, form, rules } = toRefs(data);


const toggleSelection = (rows) => {
	      // proxy.$refs["tcProjectTpRef"].toggleRowSelection(row);
			// console.log(proxy.$refs["tcProjectTpRef"])  
		if (rows) {
			// console.log(tcProjectTpRef.value)  
			// console.log(proxy.$refs["tcProjectTpRef"])  
			rows.forEach((row) => {
			  // TODO: improvement typing when refactor table
			  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
			  // @ts-expect-error
			  if(tcProjectTpRef.value!=null){
				  // console.log(row)
				  for(let i of tcProjectList.value){
					  if(i.id == row.projectid) tcProjectTpRef.value.toggleRowSelection(i,true);
				  }
				}
			})
		} else {
			// tcProjectTpRef.value!.clearSelection()
			if(tcProjectTpRef.value!=null){
				tcProjectTpRef.value.clearSelection();//清空复选框
			}
		}
	

}
/** 复选框选中数据 */
function handleTcProjectTpSelectionChange(selection) {
  // checkedTcProjectTp.value = selection.map(item => item.id)
  checkedTcProjectTp.value = selection.map(item => {return {"tcnameid":null,"projectid":item.id}});
  // console.log(checkedTcProjectTp.value);
}
/** 查询体测项目列表 */
function getProjectList() {
  loading.value = true;
  listProject(tmpProPar).then(response => {
    tcProjectList.value = response.rows;
    loading.value = false;
  });
}

/** 查询体测名称分类 用于区分哪次体测  本次体测的项目列表 */
function getList() {
  loading.value = true;
  listTcname(queryParams.value).then(response => {
    tcnameList.value = response.rows;
    total.value = response.total;
    loading.value = false;
	getTcTypeList();
  });
}
 function getTcTypeList() {
   loading.value = true;
   tmpGetPar.xmflStatus='1';
   listTctype(tmpGetPar).then(response => {
     tctypeList.value = response.rows;
     loading.value = false;
 	 getProjectList();
   });
 }
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    tcname: null,
    tcxxid: null,
    createby: null,
    sd: null,
    ed: null,
    typeid: tctypeList.value[0].id
  };
  // tcTcnameTpList.value = [];
  
  checkedTcProjectTp.value=[];
  toggleSelection();
  
  proxy.resetForm("tcnameRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  auform.value=false;
  reset();
  open.value = true;
  title.value = "添加体测名称分类 用于区分哪次体测  本次体测的项目";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  auform.value=false;
  reset();
  const _id = row.id || ids.value
  getTcname(_id).then(response => {
    form.value = response.data;
	console.log(form.value)
    // tcTcnameTpList.value = response.data.tcTcnameTpList;
    open.value = true;
    title.value = "修改体测名称分类 用于区分哪次体测  本次体测的项目";
	nextTick(() => {
	  // console.log(tcProjectTpRef.value)
		toggleSelection(response.data.tcTcnameTpList);
	});
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["tcnameRef"].validate(valid => {
    if (valid) {
      // form.value.tcTcnameTpList = tcTcnameTpList.value;
	  form.value.tcTcnameTpList = checkedTcProjectTp.value;
	  console.log(form.value)
      if (form.value.id != null) {
        updateTcname(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTcname(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

 function getDeptInfo(){
 		// console.log(userStore.user)
 		if(checkRole(['admin','common'])){
			
			dept_self.value.push({"value":-1,"label":'全部通用'});
 			listDept(tmpGetPar).then(response => {
 			  	response.data.forEach(function (element) {
 			  	  // 遍历数组，对每个元素进行操作
 				   if(element.xxlevel !=null && element.xxlevel != ''){
 						dept_self.value.push({"value":element.deptId,"label":element.deptName});
 				   }
 			  	});
 				queryParams.value.sjXxid=dept_self.value[0].value;
 				// getClassList(null);
 			});
 			// isXxidFlag.value=false;
 		}else{
 			dept_self.value.push({"value":userStore.user.deptId,"label":userStore.user.dept.deptName});
 			queryParams.value.sjXxid=dept_self.value[0].value;
 			// isXxidFlag.value=true;
 			// getClassList(queryParams.value.sjXxid);
 		}
 }


/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除体测名称分类 用于区分哪次体测  本次体测的项目编号为"' + _ids + '"的数据项？').then(function() {
    return delTcname(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 体测名称分类  体测项目关联序号 */
function rowTcTcnameTpIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 体测名称分类  体测项目关联添加按钮操作 */
// function handleAddTcTcnameTp() {
//   let obj = {};
//   tcTcnameTpList.value.push(obj);
// }

/** 体测名称分类  体测项目关联删除按钮操作 */
function handleDeleteTcTcnameTp() {
  if (checkedTcTcnameTp.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的体测名称分类  体测项目关联数据");
  } else {
    const tcTcnameTps = tcTcnameTpList.value;
    const checkedTcTcnameTps = checkedTcTcnameTp.value;
    tcTcnameTpList.value = tcTcnameTps.filter(function(item) {
      return checkedTcTcnameTps.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleTcTcnameTpSelectionChange(selection) {
  checkedTcTcnameTp.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('tcname/tcname/export', {
    ...queryParams.value
  }, `tcname_${new Date().getTime()}.xlsx`)
}


onMounted(() => {
 getList();
 getDeptInfo();
})
</script>
